package com.jstyle.beatecg.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.jstyle.beatecg.R;
import com.jstyle.beatecg.base.BaseActivity;
import com.jstyle.beatecg.daoManager.UserInfoDaoManager;
import com.jstyle.beatecg.minterface.DialogDataListener;
import com.jstyle.beatecg.model.BleData;
import com.jstyle.beatecg.model.UserInfo;
import com.jstyle.beatecg.util.GlobalConast;
import com.jstyle.beatecg.util.ImageUtils;
import com.jstyle.beatecg.util.LanguageHelp;
import com.jstyle.beatecg.util.RxBus;
import com.jstyle.beatecg.util.ScreenUtils;
import com.jstyle.beatecg.util.SharePreferenceUtils;
import com.jstyle.beatecg.view.EditTextWithDelete;
import com.jstyle.beatecg.view.FeedBackDialog;
import com.jstyle.beatecg.view.HeadCircleView;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * 用户信息
 */
public class UserInfoActivity extends BaseActivity implements DialogDataListener {

    @BindView(R.id.ll_title)
    LinearLayout llTitle;
    @BindView(R.id.bt_usetinfo_back)
    ImageView btUsetinfoBack;
    @BindView(R.id.iv_userinfo_icon)
    ImageView ivUserinfoIcon;
    @BindView(R.id.bt_userinfo_changeIcon)
    Button btUserinfoChangeIcon;
    @BindView(R.id.bt_userinfo_name)
    Button btUserinfoName;

    @BindView(R.id.tv_userinfo_phonenumber)
    Button tvUserinfoPhonenumber;

    @BindView(R.id.bt_userinfo_save)
    Button btUserinfoSave;
    @BindView(R.id.bt_user_gender)
    Button btUserGender;
    @BindView(R.id.bt_userinfo_Height)
    Button btUserinfoHeight;
    @BindView(R.id.bt_userinfo_weight)
    Button btUserinfoWeight;
    @BindView(R.id.bt_userinfo_birthday)
    Button btUserinfoBirthday;
    private Uri caremaUri;
    private Bitmap bm;
    private HeadCircleView circleView;
    private Disposable subscription;
    List<String> genderList = new ArrayList<>();
    List<String> ageList = new ArrayList<>();
    List<String> heightList = new ArrayList<>();
    List<String> weightList = new ArrayList<>();
    int infoType = 0;
    final int Info_Gender = 0;
    final int Info_Height = 1;
    final int Info_Weight = 2;
    final int Info_Age = 3;
    private UserInfo userInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_info);
        ButterKnife.bind(this);

        showStatusBar();
        subscription = RxBus.getInstance().toObservable(BleData.class).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<BleData>() {
            @Override
            public void accept(BleData bleData) throws Exception {
                String action = bleData.getAction();
                if ("finish".equals(action)) {
                    finish();
                }
            }
        });
        initData();
        showUserInfo();
        LanguageHelp.changeAppLanguage(this);
    }

    private void initData() {
        genderList.add(getString(R.string.male));
        genderList.add(getString(R.string.female));
        weightList = getListData(20, 221);
        heightList = getListData(100, 231);
        ageList = getListData(5, 131);
        String account=SharePreferenceUtils.account_default;
         userInfo= UserInfoDaoManager.getUser(account);
        if(userInfo==null){
            userInfo=new UserInfo();
            userInfo.setPhone(account);
            UserInfoDaoManager.insertUser(userInfo);
        }


    }

    private List<String> getListData(int start, int end) {
        List<String> list = new ArrayList<>();
        for (int i = start; i < end; i++) {
            list.add(String.format("%02d", i));
        }
        return list;
    }

    private void showUserInfo() {
        String phone = SharePreferenceUtils.getSpString(SharePreferenceUtils.KEY_PHONE);
        tvUserinfoPhonenumber.setText(phone);
        String name = userInfo.getName();
        btUserinfoName.setText(TextUtils.isEmpty(name) ? GlobalConast.DEFAULT_NAME : name);
        int age=userInfo.getAge();
        int weight=userInfo.getWeight();
        int height=userInfo.getHeight();
        int gender=userInfo.getGender();
        btUserinfoBirthday.setText(String.valueOf(age)+getString(R.string.yearsold));
        tvUserinfoPhonenumber.setText(gender==0?getString(R.string.male):getString(R.string.female));
        btUserinfoWeight.setText(String.valueOf(weight)+"kg");
        btUserinfoHeight.setText(String.valueOf(height)+"cm");
        setHeadIcon();
    }

    @Override
    protected void showStatusBar() {
        ScreenUtils.setStatusBarColor(llTitle, getResources().getColor(R.color.colorPrimary));
    }

    @OnClick({R.id.bt_userinfo_Height, R.id.bt_userinfo_weight, R.id.bt_userinfo_birthday, R.id.bt_usetinfo_back, R.id.bt_userinfo_changeIcon,
            R.id.bt_userinfo_name, R.id.tv_userinfo_phonenumber, R.id.bt_userinfo_save,
    R.id.bt_userinfo_birthdayRt,R.id.bt_userinfo_weightRT,R.id.bt_userinfo_HeightRt,R.id.tv_userinfo_phonenumberRt,
    R.id.bt_userinfo_nameRt,R.id.bt_userinfo_changeIconRt})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_usetinfo_back:
                finish();
                break;
            case R.id.tv_userinfo_phonenumberRt:
            case R.id.tv_userinfo_phonenumber:
                infoType = Info_Gender;
                showUserInfoDialog(genderList,infoType);
                break;
            case R.id.bt_userinfo_changeIconRt:
            case R.id.bt_userinfo_changeIcon:
                showChangeIconDialog();
                break;
            case R.id.bt_userinfo_nameRt:
            case R.id.bt_userinfo_name:
                showUserNameDialog();
                break;
            case R.id.bt_userinfo_HeightRt:
            case R.id.bt_userinfo_Height:
                infoType = Info_Height;
                showUserInfoDialog(heightList,infoType);
                break;
            case R.id.bt_userinfo_weight:
            case R.id.bt_userinfo_weightRT:
                infoType = Info_Weight;
                showUserInfoDialog(weightList,infoType);
                break;
            case R.id.bt_userinfo_birthday:
            case R.id.bt_userinfo_birthdayRt:
                infoType = Info_Age;
                showUserInfoDialog(ageList,infoType);
                break;
            case R.id.bt_userinfo_save:
                saveUserInfo();
                finish();
                break;
        }
    }

    private void showUserInfoDialog(List<String> infoList,final int type) {
        final  FeedBackDialog feedBackDialog = new FeedBackDialog(this, infoList, R.style.jstyleDialog_style);
        feedBackDialog.setDialogDataListener(this);
        feedBackDialog.show();
        llTitle.postDelayed(new Runnable() {
            @Override
            public void run() {
                switch (type){
                    case 0://男女
                        int index=userInfo.getGender()==0?0:1;
                        feedBackDialog.wheelViewTopicindex(index,true);
                        break;
                    case 1://身高
                        int indexheight = heightList.indexOf(userInfo.getHeight()+"");
                        feedBackDialog.wheelViewTopicindex(indexheight,true);
                        break;
                    case 2://体重
                        int indexweight = weightList.indexOf(userInfo.getWeight()+"");
                        feedBackDialog.wheelViewTopicindex(indexweight,true);
                        break;
                    case 3://年龄
                        int indexAge = ageList.indexOf(userInfo.getAge()+"");
                        feedBackDialog.wheelViewTopicindex(indexAge,true);
                        break;
                }
            }
        },200);
    }

    private void showUserNameDialog() {
        final EditTextWithDelete editTextWithDelete = new EditTextWithDelete(this);
        editTextWithDelete.setText(btUserinfoName.getText().toString());
        if(LanguageHelp.isEnglish()){
            editTextWithDelete.setFilters( new  InputFilter[]{ new  InputFilter.LengthFilter(10)});//限制最大输入字符16
        }else{
            editTextWithDelete.setFilters( new  InputFilter[]{ new  InputFilter.LengthFilter(8)});//限制最大输入字符16
        }
        AlertDialog dialog = new AlertDialog.Builder(this).setMessage(getString(R.string.Nickname)).setNegativeButton(getString(R.string.cancel), null).setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String name = editTextWithDelete.getText().toString();
                if(TextUtils.isEmpty(name))return;
                userInfo.setName(name);
                btUserinfoName.setText(name);
            }
        }).create();
        dialog.setView(editTextWithDelete, ScreenUtils.dip2px(this, 16), 0, ScreenUtils.dip2px(this, 16), 0);
        dialog.show();
    }

    private void showChangeIconDialog() {
        AlertDialog dialog = new AlertDialog.Builder(this).setItems(R.array.change_icon, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (which == 1) {
                    caremaUri = ImageUtils.createImagePathUri(UserInfoActivity.this);
                    ImageUtils.openCameraImage(UserInfoActivity.this, caremaUri);
                } else {
                    ImageUtils.openLocalImage(UserInfoActivity.this);
                }
            }
        }).setPositiveButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        }).create();
        dialog.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) return;
        switch (requestCode) {
            case ImageUtils.CROP_IMAGE:
                setHeadIcon();
                break;
            case ImageUtils.GET_IMAGE_BY_CAMERA:
                ImageUtils.cropImage(this, ivUserinfoIcon.getWidth() * 2,
                        ivUserinfoIcon.getHeight() * 2, caremaUri, ImageUtils.tempUri);
                break;
            case ImageUtils.GET_IMAGE_FROM_PHONE:
                ImageUtils
                        .cropImage(this, ivUserinfoIcon.getWidth() * 2,
                                ivUserinfoIcon.getHeight() * 2, data.getData(),
                                ImageUtils.tempUri);
                break;
            default:
                break;
        }
    }

    private void setHeadIcon() {

        bm = ImageUtils.findHeadBitmap(this) == null ? BitmapFactory.decodeResource(getResources(),
                R.drawable.user_icon) : ImageUtils.findHeadBitmap(this);
        circleView = new HeadCircleView(bm);
        ivUserinfoIcon.setImageDrawable(circleView);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unsubscribe();
    }

    private void unsubscribe() {
        if (subscription != null && !subscription.isDisposed()) {
            subscription.dispose();
        }
    }

    @Override
    public void dataListener(String data) {

    }

    @Override
    public void dataListener(int position) {
        switch (infoType) {
            case Info_Age:
                userInfo.setAge(Integer.valueOf(ageList.get(position)));
                btUserinfoBirthday.setText(ageList.get(position)+getString(R.string.yearsold));
                break;
            case Info_Gender:
                userInfo.setGender(position);
                tvUserinfoPhonenumber.setText(genderList.get(position));
                break;
            case Info_Weight:
                userInfo.setWeight(Integer.valueOf(weightList.get(position)));
                btUserinfoWeight.setText(weightList.get(position)+"kg");
                break;
            case Info_Height:
                userInfo.setHeight(Integer.valueOf(heightList.get(position)));
                btUserinfoHeight.setText(heightList.get(position)+"cm");
                break;
        }
    }
    private void saveUserInfo() {

       UserInfoDaoManager.insertUser(userInfo);
    }

}
